package com.swm.rest;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.List;

import javax.activation.DataHandler;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.attachment.AttachmentMarshaller;
import javax.xml.soap.Node;
import javax.xml.validation.Schema;

import org.xml.sax.InputSource;

import com.swm.model.MyProject;
import com.swm.model.Project;
import com.swm.model.Testcase;
import com.swm.model.User;

public class JAXBConverter {

	private static JAXBConverter converter = null;
	public static JAXBConverter getInstance(){
		if ( converter == null ){
			converter = new JAXBConverter();
		}
		return converter;
	}
	
	public JAXBContext createJAXBContext( ModelEnum type ) throws JAXBException{
		switch ( type )
		{
		case MODEL_USER:	
			return JAXBContext.newInstance( User.class );				
		case MODEL_PROJECT:
			return JAXBContext.newInstance( Project.class );		
		case MODEL_TESTCASE:
			return JAXBContext.newInstance( Testcase.class );
		case MODEL_MYPROJECT:
			return JAXBContext.newInstance( MyProject.class );
		}
		return null;
	}
	
	public void convertXMLToFile( User obj, ModelEnum type ) throws JAXBException {		
		File file = new File("temp.xml");
				
		JAXBContext jaxbContext = createJAXBContext( type );		
		if ( jaxbContext != null ){
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.marshal( obj, file );
		}
	}
	
	public String convertXML( Object obj, ModelEnum type ) throws JAXBException {						
		
		StringWriter sw = new StringWriter();
		
		JAXBContext jaxbContext = createJAXBContext( type );	
		if ( jaxbContext != null ){
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.marshal( obj, sw );		
			
			//System.out.println("[Result] = " + sw.getBuffer().toString() );
			return sw.getBuffer().toString();
		}
		return null;
	}
	
	public Object convertJava( String xml, ModelEnum type ) throws JAXBException{		
		InputStream is 			= new ByteArrayInputStream( xml.getBytes() );
		InputSource xmlsource 	= new InputSource( is );
		
		JAXBContext jaxbContext = createJAXBContext( type );				
		if ( jaxbContext != null ){		
			Unmarshaller unmarshaller =jaxbContext.createUnmarshaller();	
			return unmarshaller.unmarshal( xmlsource );
		}
		return null;
	}	
}
